package DAO;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import Model.user;
/**
 * 用户DAO
 * 不操作session
 * @author MacBook
 *
 */
@SuppressWarnings("deprecation")
public class userDAO {
	//添加用户
	public static void save(Session session,user u){
		u.setPower("normal");
		session.save(u);
	}
	//更改用户
	public static void update(Session session,user u){
		session.update(u);
	}
	//用户名查找用户
	@SuppressWarnings("deprecation")
	public static user findByUsername(Session session,String username){
		String hql = "from user where username = ?";
		Query<?> query = session.createQuery(hql);
		query.setParameter(0, username);
		List list = query.list();
		user u = null;
		if(list.size() != 0)
			u = (user) list.get(0);
		return u;
	}
	//根据用户名、邮箱、手机号查找用户
	public static user findByMessages(Session session,String username,String email,String tel){
		String hql = "from user where username = ? and email = ? and tel =?";
		Query<?> query = session.createQuery(hql);
		query.setParameter(0, username);
		query.setParameter(1, email);
		query.setParameter(2, tel);
		List list = query.list();
		user u = null;
		if(list.size() != 0)
			u = (user) list.get(0);
		return u;
	}
	//用户名和密码查找用户
	public static user FindbyNameAndPassword(Session session,String username,String password){
		String hql = "from user where username = ? and password = ?";
		Query<?> query = session.createQuery(hql);
		query.setParameter(0, username);
		query.setParameter(1, password);
		List list = query.list();
		user u = null;
		if(list.size() != 0)
			u = (user) list.get(0);
		return u;
	}
	//更改密码
	public static void updatePasswordByUsername(Session session,String username,String password){
		String hql = "update user set password = ? where username = ?";
		Query<?> query = session.createQuery(hql);
		query.setParameter(0, password);
		query.setParameter(1, username);
		query.executeUpdate();
	}
	//查找所有用户
	@SuppressWarnings("deprecation")
	public static List<user> findAll(Session session){
		String hql = "select new user(username,email,sex,tel) from user";
		Query<?> query = session.createQuery(hql);
		List list = query.list();
		return list;
	}
	//删除用户
	public static void delete(Session session,user u){
		session.delete(u);
	}
}
